//
//  EFADeviceResultsTVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/9/15.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADeviceResultsTVC.h"
#import "EFADeviceTCell.h"
#import <UIScrollView+EmptyDataSet.h>
#import "EFAModel.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "EFAPjtDeviceAddVC.h"
#import "EFADeviceInfoVC.h"

@interface EFADeviceResultsTVC () <DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFADeviceTCellDelegate>
@property (strong, nonatomic) NSMutableArray *searchPoiArray;
@property (strong, nonatomic) EFADeviceModel *deviceModel;
@end

static NSString *const kReuseCellId = @"EFADeviceTCell";
//static NSInteger const kRequestSize = 20;

@implementation EFADeviceResultsTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initSubViews];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
//    if (@available(iOS 11.0, *)) { // 这里并不是布局的问题，仅仅是为了适配mjrefresh的下拉动画效果
//        if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
//            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//            CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
//            CGFloat navHeight = CGRectGetHeight(self.navigationController.navigationBar.frame);
//            CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
//            UIEdgeInsets edgeInsets = UIEdgeInsetsMake(statusHeight + navHeight, 0, tabHeight, 0);
//            self.tableView.contentInset = edgeInsets;
//            self.tableView.scrollIndicatorInsets = edgeInsets;
//        }
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有搜到相关设备" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.deviceModel.device_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFADeviceTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.deviceModel.device_list.count) {
        [cell configViewWithDeviceListItem:self.deviceModel.device_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.deviceModel.device_list.count) {
        [self jumpToDeviceInfoWithDeviceListItem:self.deviceModel.device_list[indexPath.row]];
    }
}

#pragma mark - EFADeviceTCellDelegate
- (void)deviceTCell:(EFADeviceTCell *)cell deviceNoteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row < self.deviceModel.device_list.count) {
        EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeDetail];
        vc.deviceItem = self.deviceModel.device_list[indexPath.row];
        [self.presentingViewController showViewController:vc sender:nil];
    }
}

#pragma mark - event responds
- (void)refreshNewData {
    [self requestDeviceListWithHeader:YES];
}

#pragma mark - private methods
- (void)jumpToDeviceInfoWithDeviceListItem:(EFADeviceListItem *)item {
    EFADeviceInfoVC *vc = [[EFADeviceInfoVC alloc] init];
    vc.deviceId = item.efairydevice_id;
    vc.device_name = item.efairydevice_name;
    [self.presentingViewController showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
//    NSLog(@"停止刷新是否是头部---%zd", isHeader);
//    if (isHeader) {
//        [self.tableView.mj_header endRefreshing];
//    } else {
//        [self.tableView.mj_footer endRefreshing];
//    }
}

- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestDeviceListWithHeader:isHeader];
}
- (EFADeviceModel *)deviceListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.deviceModel;
    }
    
    EFADeviceModel *temp = [EFADeviceModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.deviceModel;
    }
    
    if (AddMore && self.deviceModel) {
        [self.deviceModel addMoreWithData:temp];
    } else {
        self.deviceModel = temp;
    }
    return self.deviceModel;
}
#pragma mark - network request
- (void)requestDeviceListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    if (self.project_id) {
        [pars setObject:@(self.project_id) forKey:@"efairyproject_id"];
    }
    if (self.keywords) {
        [pars setObject:self.keywords forKey:@"keyword"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if (self.project_id) {
            [self deviceListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            self.deviceModel = [[EFAModel sharedInstance] deviceModelWithDictionary:responseObject];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - gettes and setters

@end
